﻿using AutoMapper;
using B.S.AuthCenter.Api.Write.Application.Command.Roles;
using B.S.AuthCenter.Domain;
using B.S.AuthCenter.ErrorCount;
using B.S.AuthCenter.InfrasIntructure.Interface;
using MediatR;
using System.Transactions;

namespace B.S.AuthCenter.Api.Write.Application.Handler.Roles
{
    public class AddUserRoleHandler : IRequestHandler<AddUserRoleCommand, ApiResult<int>>
    {
        IBaseRepository<UserModel> userRepo;
        IBaseRepository<RoleModel> roleRepo;
        IBaseRepository<UserRoleModel> urRepo;
        IMapper mapper;

        public AddUserRoleHandler(IBaseRepository<UserModel> userRepo, IBaseRepository<RoleModel> roleRepo, IBaseRepository<UserRoleModel> urRepo, IMapper mapper)
        {
            this.userRepo = userRepo;
            this.roleRepo = roleRepo;
            this.urRepo = urRepo;
            this.mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(AddUserRoleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var userolw = urRepo.GetAll().Where(x => x.Rid == request.Rid).ToList();

           foreach(var item in userolw)
            {
               
                    item.IsDeleted = true;
                await urRepo.UpdateAll(userolw);
            }
          
            var list = request.Uid.Split(',').Select(x => Convert.ToInt32(x)).ToList();
            foreach (var item in list)
            {
                UserRoleModel userRoleModlel = new UserRoleModel();
                userRoleModlel.Uid = item;
                userRoleModlel.Rid = request.Rid;

                await urRepo.Add(userRoleModlel);

            }

            res.Code = ApiEnum.Success;
            res.Msg = "分配用户成功";
            res.Data = list;
            return await Task.FromResult(res);

        }
    }
}
